package com.qd.push.service;

import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.push.mapper.HkParkOrderMapper;
import com.qd.push.model.HkParkOrder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 临停订单
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class HkParkOrderService extends BaseService<HkParkOrderMapper, HkParkOrder> {
    private static final String PREFIX_ID = "panda_hk_park_order_orderLogId_{0}";
    private final RedisTemplateUtil<HkParkOrder> redisTemplateUtil;

    /**
     * 根据主键获取数据
     *
     * @param orderLogId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public HkParkOrder getById(String orderLogId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, orderLogId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(orderLogId), HkParkOrder.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateById(String orderLogId, String billCode) {
        HkParkOrder hkParkOrder = getById(orderLogId);
        if (null == hkParkOrder) {
            return;
        }
        if (!hkParkOrder.getBillCode().equals(billCode)) {
            try {
                HkParkOrder update = new HkParkOrder();
                update.setOrderLogId(orderLogId);
                update.setBillCode(billCode);
                getBaseMapper().updateById(update);
                update.freeData();
            } finally {
                redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, orderLogId));
            }
        }
        hkParkOrder.freeData();
    }
}